<?php
/**
 * @package es2reveng
 * @name ES2 .ENG/.GER/.FRE/.STR string resource viewer
 * @author marco 'harddisk' schuster
 * @license GPL v3
 */
require 'helpers.php';
$f = $argv[1];
echo "viewing file $f\n";
if (!is_file($f))
	die("file broken");
$fp = fopen($f, "rb");
$type = strtolower(pathinfo($f, PATHINFO_EXTENSION));

//check file size
$offset = -1; //the ++ incrementor will read at byte 1 if this is omitted
$b1 = getchar($fp, ++$offset, false);
$b2 = getchar($fp, ++$offset, false);
$b3 = getchar($fp, ++$offset, false);
$b4 = getchar($fp, ++$offset, false);
$flen = le_to_int($b1, $b2,$b3,$b4);
echo "file is $flen bytes long\n";
if ($flen + 4 != filesize($f))
	echo "warning: file size in header (".($flen + 4)." bytes) differs from actual file size (".filesize($f)." bytes).\nthis file may contain strange messages.\n";


//get msg count
$nl = getchar($fp, ++$offset, false);
$nh = getchar($fp, ++$offset, false);
$num_msgs = le_to_int($nl, $nh);
echo "this file is supposed to carry $num_msgs entries\n";

for ($i = 0; $i < $num_msgs; $i++) {
	echo "begin reading at offset ".dechex($offset)."\n";
	$ml = getchar($fp, ++$offset, false);
	$mh = getchar($fp, ++$offset, false);
	$msg_len = le_to_int($ml, $mh);
	echo "message $i is $msg_len bytes long\n";
	$buf = "";
	for ($j = 0; $j < $msg_len; $j++) {
		$buf .= getchar($fp, ++$offset);
	}
	echo "message $i is '$buf'\n";

	//jump over the duplicated NUL byte at the end of each msg
	if (getchar($fp, ++$offset, false) != 0)
		echo "warning at offset 4: jumping over something which is NOT a dupe null byte!\n";
}

if ($offset - 1 != filesize($f))
	echo "arrived at structural end (offset is $offset, flen is ".filesize($f)."), but there are still some bytes left\n";
else
	echo "file parse OK\n";
?>